package com.redis.springbootredis.rabbitmq.test;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @create 2020-11-03 20:13
 * 死信队列的消费者
 */
public class ExchangeDlxConsumer {

    public static void main(String[] args) throws Exception {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置访问的ip地址
        connectionFactory.setHost("192.168.238.132");
        //设置虚拟主机(类似于redis的db)
        connectionFactory.setVirtualHost("ljw");
        connectionFactory.setPort(5672);
        //设置密码和账户
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //新建连接对象
        Connection connection = connectionFactory.newConnection();
        //创建连接信道(需要通信的话必须创建，类似于输送水的水管)
        Channel channel = connection.createChannel();
        //定义交换机
        channel.exchangeDeclare("exchangetestdlx", BuiltinExchangeType.TOPIC,true);
        //定义队列
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl",10000);
        /*
          设置消息过期后处理此消息的死信交换机和队列
          x-dead-letter-exchange 绑定死信交换机
        */
        arguments.put("x-dead-letter-exchange","exchangedlx");
        arguments.put("x-dead-letter-routing-key","routingkeydlx");
        channel.queueDeclare("Queuetestdlx",true,
                false,false,arguments);
        //将队列绑定到交换机
        channel.queueBind("Queuetestdlx","exchangetestdlx","#.routingkeytestdlx.#");

        //定义死信交换机和死信队列
        channel.exchangeDeclare("exchangedlx",BuiltinExchangeType.TOPIC,true);
        channel.queueDeclare("queuedlx",true,false,false,null);
        //将队列绑定到死信交换机上
        channel.queueBind("queuedlx","exchangedlx","#.routingkeydlx.#");
        //创建消费者
        channel.basicConsume("queuedlx", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                 //输出信息查看
                System.out.println("consumerTag---"+consumerTag);
                System.out.println("body---"+new String(body));
                System.out.println("properties---"+properties.getHeaders());
                System.out.println("消费成功");
            }
        });
    }
}
